<template>
  <div
    :id="compId"
    class="px-4 h-full overflow-y-auto pb-20 overscroll-contain"
    @scroll.passive="checkScrollPosition"
  >
    <VirtualWaterfall
      v-if="!(data.loading && data.pageNum === 1)"
      :virtual="waterfalOptions.virtual"
      :gap="waterfalOptions.gap"
      :min-column-count="waterfalOptions.minColumnCount"
      :max-column-count="waterfalOptions.maxColumnCount"
      :preload-screen-count="[1, 1]"
      :items="data.list"
      :calc-item-height="calcItemHeight"
    >
      <template #default="{ item }: { item: Model }">
        <Card
          :data="item"
          :key="item.model_code"
          :selected="isSelected(item.model_code)"
          @click="handleCardTap(item)"
        />
      </template>
    </VirtualWaterfall>
    <div v-else class="w-full h-full" flex="~ justify-center items-center"><Loading /></div>
    <div id="loading-wrapper" v-show="data.loading && data.pageNum !== 1"><Loading /></div>
  </div>
</template>

<script setup lang="ts">
import { VirtualWaterfall } from '@lhlyu/vue-virtual-waterfall'
import type { Model } from '@/service/types'
import Card from './Card.vue'
import Loading from '@/components/Loading.vue'
import { modelsGetter } from '@/service/methods/feed'
import { useRequest } from 'alova'
import { selectedModelsProvider } from '../../useCreate'

const props = defineProps<{
  categoryCode: string
  enableTouchMove: (v: boolean) => void
}>()
const {
  selectedModels,
  updateModelList,
  moveModelList
}: {
  selectedModels: globalThis.Ref<Model[]>
  updateModelList: (models: Model[], categoryCode?: string) => void
  moveModelList: (categoryCode?: string) => void
} = inject<any>(selectedModelsProvider, { selectedModels: [] })
const compId = computed(() => `ModelsOfGroup-${props.categoryCode}`)
const waterfalOptions = {
  virtual: false,
  gap: 12,
  maxColumnCount: 3,
  minColumnCount: 3,
  bottomDistance: 100
}
const data = reactive({
  loading: false,
  pageNum: 1,
  pageSize: 24,
  total: 0,
  list: [] as Model[],
  end: false
})
const { send: loadModels, onComplete } = useRequest(
  () =>
    modelsGetter({
      page_num: data.pageNum,
      page_size: data.pageSize,
      category_code: props.categoryCode
    }),
  { immediate: false }
)
onComplete(() => {
  data.loading = false
})
const loadData = async () => {
  if (data.end) return
  data.loading = true
  const result = await loadModels()
  if (result.data.length == 0) {
    data.end = true
    return
  }
  data.pageNum++
  data.total = result.total
  for (const item of result.data) {
    const hasItem = data.list.find((ele) => ele.model_code === item.model_code)
    if (!hasItem) {
      data.list.push(item)
    }
  }
  if (data.list.length >= data.total) data.end = true
}
const onEnter = ()=>{
  console.log('onEnter',props.categoryCode)
  if(!data.list.length) {
    loadData()
  }
}
defineExpose({onEnter})
const calcItemHeight = (item: Model, itemWidth: number) => {
  return itemWidth + 25
}

// 检查是否加载更多
const checkScrollPosition = async () => {
  if (data.loading) {
    return
  }
  const container = document.getElementById(compId.value)
  if (!container) return
  const scrollHeight = container.scrollHeight
  const scrollTop = container.scrollTop
  const clientHeight = container.clientHeight

  const distanceFromBottom = scrollHeight - scrollTop - clientHeight

  // 不大于最小底部距离就加载更多
  if (distanceFromBottom <= waterfalOptions.bottomDistance) {
    await loadData()
  }
}

const isSelected = (modelCode?: string) => {
  const model = selectedModels.value?.find((item) => item.model_code === modelCode)
  return !!model
}
const handleCardTap = (model: Model) => {
  // 判断是否存在同类型的模型
  // 如果有就替换
  // 没有就添加到列表
  const target = selectedModels.value.find((item) => item.category_code === model.category_code)
  const newMap = new Map(selectedModels.value.map((item) => [item.category_code!, item]))
  if (target) {
    newMap.set(target.category_code!, model)
  } else {
    newMap.set(model.category_code!, model)
    moveModelList()
  }
  const arr = Array.from(newMap.values())
  updateModelList(arr, model.category_code)
}
onMounted(() => {
  console.log('models of group mounted')
  loadData()
})
</script>

<style scoped>
#loading-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 5rem;
  .loader {
    font-size: 25px;
  }
}
</style>
